package com.changgou.web.gateway.filter;

import com.changgou.web.gateway.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: 陈安
 * @Date: 2020/12/14$ 20:50$
 * @Description: $todo$
 * @Version 1.0
 */
@Component
public class AuthFilter implements GlobalFilter,Ordered {
    @Autowired
    private AuthService authService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断当前的请求路径是不是登录路径,如果是则直接放行
        String path = request.getURI().getPath();
//        if("/api/oauth/login".equals(path)||"/api/oauth/toLogin".equals(path)){
        if("/api/oauth/login".equals(path)|| !UrlFilter.hasAuthorize(path)){
            //是登录我们直接放行
            return chain.filter(exchange);
        }

        //从cookie中获取jti的值,如果该值不存在就直接拒绝本次访问
        String jti=authService.getJtiFromCookie(request);
        if(StringUtils.isEmpty(jti)){
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        //如果cookie中有jti的值,我们就去redis中获取jwt的值,如果不存在就拒接本次访问
        String jwt = authService.getJwtFromRedis(jti);
        //这是在redis里面的,所以有可能已经过期了,所有也有可能不存在
        if(StringUtils.isEmpty(jwt)){
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        //对当前的请求对象让他携带令牌的信息
        request.mutate().header("Authorization", "Bearer " + jwt);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
